/*
用原生http方式渲染模板
*/
package main

import (
	"fmt"
	"html/template"
	"net/http"
)

type User struct {
	Name   string
	Gender string
	Age    int
}

func sayhello(w http.ResponseWriter, r *http.Request) {
	kua := func(name string) (string, error) {
		return name + "good man", nil
	}
	//定义模板
	t := template.New("hello.tmpl") //创建模板对象,模板对象名要和模板文件名对应
	t.Funcs(template.FuncMap{
		"kua": kua, //将自定义函数加入模板对象中
	})
	t, err := t.ParseFiles("../hello.tmpl") //用对象解析模板文件
	if err != nil {
		fmt.Println("Parse templates failed,err:", err)
		return
	}
	//解析模板
	u1 := User{
		Name:   "Jordan",
		Gender: "男",
		Age:    18,
	}

	hobbylist := []string{
		"篮球",
		"足球",
	}

	m1 := map[string]interface{}{
		"name":   "stormfat",
		"gender": "男",
		"age":    40,
	}
	name := "小明"
	//渲染模板
	err = t.Execute(w, map[string]interface{}{
		"u1":    u1,
		"m1":    m1,
		"hobby": hobbylist,
		"name":  name,
	})
	if err != nil {
		return
	}
}

func main() {
	http.HandleFunc("/", sayhello)
	err := http.ListenAndServe(":9000", nil)
	if err != nil {
		fmt.Println("Server start err:", err)
		return
	}

}
